package cn.sc.hunter.framework;

import cn.sc.hunter.framework.bean.Handler;
import cn.sc.hunter.framework.helper.BeanHelper;
import cn.sc.hunter.framework.helper.ConfigHelper;
import cn.sc.hunter.framework.helper.ControllerHelper;
import cn.sc.hunter.framework.util.CodecUtil;
import cn.sc.hunter.framework.util.StreamUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求转发器
 */
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 初始化对应的 Helper 类
        HelperLoader.init();
        // 获取 ServletContext 对象（用于注册 Servlet）
        ServletContext context = config.getServletContext();
        // 注册处理 JSP 的 Servlet
        ServletRegistration jsp = context.getServletRegistration("jsp");
        jsp.addMapping(ConfigHelper.getWebViewPath() + "*");
        // 注册处理静态资源默认的 Servlet
        ServletRegistration defaultServlet = context.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getWebAssetPath() + "*");
    }

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求方法和请求路径
        String requestMethod = request.getMethod().toUpperCase();
        String requestPath = request.getPathInfo();
        // 获取 RequestMapping 处理器
        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        if (handler != null) {
            // 获取 Controller 类及实例
            Class<?> clazz = handler.getControllerClass();
            Object instance = BeanHelper.getBean(clazz);
            // 创建请求参数对象
            Map<String, Object> params = new HashMap<>();
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String key = paramNames.nextElement();
                String value = request.getParameter(key);
                params.put(key, value);
            }
            String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
        }
    }
}
